<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/03/30 11:43:36 $)
// $RCSfile: staff_downloads.php,v $ : $Revision: 1.14 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

if ($_SWIFT["staff"]["dl_entab"] == "0")
{
	echo '<font face="Verdana, Arial, Helvetica" size="2" color="red"><b>'.$_SWIFT["language"]["nopermission"].'</b></font>';
	exit;
}

require_once ("./modules/downloads/functions_downloads.php");
require_once ("./includes/functions_html.php");
require_once ("./includes/functions_template.php");
require_once ("./includes/data_mimelist.php");
require_once ("./includes/functions_jscache.php");

$template->loadLanguageSection("downloads");

$interface->assignQuickLink($_SWIFT["language"]["managecategories"], "index.php?_m=downloads&_a=managecategories", "icon_list.gif");
$interface->assignQuickLink($_SWIFT["language"]["managefiles"], "index.php?_m=downloads&_a=managefiles", "icon_managefiles.gif");
$interface->assignQuickLink($_SWIFT["language"]["insertcategory"], "index.php?_m=downloads&_a=insertcategory", "icon_newcategory.gif");
$interface->assignQuickLink($_SWIFT["language"]["insertfile"], "index.php?_m=downloads&_a=insertfile", "icon_insertfile.gif");

/**
* ###############################################
* FUNCTION DECLARATIONS
* ###############################################
*/

/**
* Callback for parsing download item data
*/
function _downloadItemFields($arg)
{
	global $_SWIFT, $_sladays, $mimelist;
	$record = &$arg[0];
	$fields = &$arg[1];
	
	$record["downloaditems.title"] = '<table width="100%"  border="0" cellspacing="0" cellpadding="2"><tr><td width="1"><img src="'. $_SWIFT["themepath"] . iif($record["categorytype"]==SWIFTPUBLIC||$record["categorytype"]=="", "icon_public", "icon_private") .'.gif" border="0" /></td>'. iif(!empty($record["itempassword"]), '<td width="1"><img src="'. $_SWIFT["themepath"] . 'icon_lock.gif" border="0" /></td>') .'<td align="left"><span class="smalltext"><a href="index.php?_m=downloads&_a=editfile&downloaditemid='. $record["downloaditemid"] .'"><b>'. $record["itemtitle"] .'</b></a></span></td></tr></table>';

	$record["downloaditems.dateline"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $record["itemdateline"]);

	$extension = getFileExtension($record["filename"]);
	$mimedata = $mimelist[$extension];
	if (!empty($mimedata[1]))
	{
		$filenamed = '<table width="100%"  border="0" cellspacing="0" cellpadding="2"><tr><td width="1"><img src="'. $_SWIFT["themepath"] . $mimedata[1] .'" border="0" /></td><td align="left"><a href="index.php?_m=downloads&_a=downloadfile&downloaditemid='.$record["downloaditemid"].'"><span class="smalltext">'. $record["filename"] .'</span></a></td></tr></table>';
	} else {
		$filenamed = '<table width="100%"  border="0" cellspacing="0" cellpadding="2"><tr><td align="left"><a href="index.php?_m=downloads&_a=downloadfile&downloaditemid='.$record["downloaditemid"].'"><span class="smalltext">'. $record["filename"] .'</span></a></td></tr></table>';
	}
	$record["downloaditems.filename"] = $filenamed;
	$record["downloaditems.filesize"] = formattedSize($record["filesize"]);
	$record["downloaditems.displayorder"] = $record["itemdisplayorder"];
	$record["downloaditems.totaldownloads"] = $record["totaldownloads"];

	if (!empty($record["filelink"]))
	{
		$record["downloaditems.filename"] = '<a href="'. $record["filelink"] .'" id="blue" target="_blank" title="'. $record["filelink"] .'"><img src="'. $_SWIFT["themepath"] .'icon_link.gif" border="0" align="absmiddle" /> '.$_SWIFT["language"]["filelinkact"]. '</a>';
	}

	$record["options"] = iif($_SWIFT["staff"]["dlcaneditfile"]!="0", '<a href="index.php?_m=downloads&_a=editfile&downloaditemid='. $record["downloaditemid"] .'" title="'. $_SWIFT["language"]["edit"] .'"><img src="'. $_SWIFT["themepath"] .'icon_edit.gif" border="0">&nbsp;'. $_SWIFT["language"]["edit"] .'</a>'). iif($_SWIFT["staff"]["dlcandelfile"]!="0", '&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["dlitemdelconfirmmsg"] .'\', \'index.php?_m=downloads&_a=managefiles&do=delete&downloaditemid='. $record["downloaditemid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;');

	return $record;
}

/**
* Mass Action: Delete Download Items
*/
function _maDeleteDownloadItems()
{
	global $dbCore, $_SWIFT, $infomessage;

	if (_is_array($_POST["itemid"]))
	{
		$infomessage = $_SWIFT["language"]["dlitemsdelconfirm"];
		deleteDownloadFiles($_POST["itemid"]);
	}
}


renderCategoryList();

/**
* ###############################################
* MANAGE CATEGORIES
* ###############################################
*/
if ($eventaction == "managecategories")
{
	if ($_GET["do"] == "delete" && !empty($_GET["downloadcategoryid"]) && $_SWIFT["staff"]["dlcandelcat"] != "0")
	{
		$totaldel = deleteDownloadCategory($_GET["downloadcategoryid"]);

		printRedirect(sprintf($_SWIFT["language"]["dlcatdeleteconfirm"], htmlspecialchars($totaldel)), "index.php?_m=downloads&_a=managecategories&catdel=".urlencode($totaldel));
		exit;
	}

	if (!empty($_REQUEST["insertcat"]))
	{
		$infomessage = sprintf($_SWIFT["language"]["dlinsertconfirm"], htmlspecialchars($_REQUEST["insertcat"]));
	} else if (!empty($_REQUEST["catdel"])) {
		$infomessage = sprintf($_SWIFT["language"]["dlcatdeleteconfirm"], htmlspecialchars($_REQUEST["catdel"]));	
	} else if (!empty($_REQUEST["updatecat"])) {
		$infomessage = sprintf($_SWIFT["language"]["dlupdateconfirm"], htmlspecialchars($_REQUEST["updatecat"]));
	}

	require_once ("./includes/TreeMenu/TreeMenu.php");
	$template->assign("treemenu", true);

	$icon = 'icon_folderyellow3.gif';
	$expandedIcon = 'icon_folderyellow3.gif';

	$menu = new HTML_TreeMenu();

	// Do we need to filter it to one user group?
	$dofilter = false;
	if ($_POST["filter"] == "1")
	{
		$dofilter = true;
	}

	// Is it filtered result?
	if ($dofilter == true)
	{
		// Build the entire download category data with filtering enabled
		$result = buildDLCategoryData(false, $_POST["filtertgroupid"]);
	} else {
		// Build the download category data WITHOUT the filtering enabled
		$result = buildDLCategoryData(false, false);
	}
	$categorydata = $result["categorydata"];
	$categoryidlist = $result["categoryidlist"];

	// Now that we have all the categories, we need to build up the items under it
	$builditems = true; // Change later on
	if ($builditems)
	{
		$itemdata = buildDLItemData($categoryidlist);
	} else {
		$itemdata = array();
	}

	// Now we build up the nodes for this..
	$menu  = new HTML_TreeMenu();

	$node1   = new HTML_TreeNode(array('text' => "&nbsp;". $_SWIFT["language"]["downloads"] ."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[". iif($_SWIFT["staff"]["dlcaninsertfile"]!="0", " <a href='index.php?_m=downloads&_a=insertfile&parentcategoryid=0' id='blue' title='". $_SWIFT["language"]["addfile"] ."'>". $_SWIFT["language"]["addfile"] ."</a>"). iif($_SWIFT["staff"]["dlcaninsertcat"]!="0", " | <a href='index.php?_m=downloads&_a=insertcategory&parentcategoryid=0' id='blue' title='". $_SWIFT["language"]["addsubcat"] ."'>". $_SWIFT["language"]["addsubcat"] ."</a> "). "]", 'link' => "", 'icon' => "icon_list.gif", 'expandedIcon' => "icon_list.gif", 'expanded' => true));

	doDLCategoryTreeLoop(0, $categorydata, $itemdata, $node1);

	$menu->addItem($node1);
	
	// Create the presentation class
	$treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => stripTrailingSlash($_SWIFT["themepath"]), 'defaultClass' => 'treeMenuDefault'));

	$interface->staffHeader($_SWIFT["language"]["downloads"]." &gt; ".$_SWIFT["language"]["managecategories"], 5);

	$interface->staffNavBar('<a href="index.php?_m=downloads&_a=managecategories" title="'.$_SWIFT["language"]["managecategories"].'">'.$_SWIFT["language"]["managecategories"].'</a>', "", 5);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	// ======= FILTER =======
	echo '<div id="filtertscat" style="DISPLAY:none;">'.SWIFT_CRLF;
	printFormStart();
	printMainTableHeader($_SWIFT["language"]["filter"]);

	$options = array();
	$index = 0;
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."templategroups` ORDER BY `title` ASC;");
	while ($dbCore->nextRecord())
	{
		$options[$index]["title"] = $dbCore->Record["title"];
		$options[$index]["value"] = $dbCore->Record["tgroupid"];
		$index++;
	}

	printSelectRow("filtertgroupid", $_SWIFT["language"]["filtertgroupid"], $_SWIFT["language"]["desc_filtertgroupid"], $options);
	printSubmitRow($_SWIFT["language"]["filter"]);
	printMainTableFooter();
	addHiddenField("_m", "downloads");
	addHiddenField("_a", "managecategories");
	addHiddenField("filter", "1");
	printFormEnd();
	echo '<BR /></div>'.SWIFT_CRLF;	


	printMainTableHeader($_SWIFT["language"]["categorylist"]);
	// ======= TOOLBAR OPTIONS =======
	echo '<tr>'.SWIFT_CRLF;
	echo '<td class="toolbarrow" align="left" colspan="2" valign="middle" nowrap><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td width="5"><img src="'. $_SWIFT["themepath"] .'grip.gif" border="0" /></td><td class="toolbarrow"><span class="toolbartext">&nbsp;<a href="index.php?_m=downloads&_a=managefiles" id="white" title="'. $_SWIFT["language"]["managefiles"] .'">'. $_SWIFT["language"]["managefiles"] .'</a>&nbsp;|&nbsp;<a href="javascript:switchDisplay(\'filtertscat\');" id="white" title="'. $_SWIFT["language"]["filter"] .'">'. $_SWIFT["language"]["filter"] .'</a></span></td></tr></table></td>'.SWIFT_CRLF;
	echo '</tr>'.SWIFT_CRLF;
	// ======= TOOLBAR OPTIONS =======

	ob_start();
	?><div style="position:relative; width:100%; height:320px; background-color:#ffffff; overflow:auto;"><?
	$treeMenu->printMenu();
	?></div><?
	$contents = ob_get_contents();
	ob_end_clean();

	printDescRow($contents, "2", "defaultrow");

	printMainTableFooter();

	$template->assign("backurl", "index.php?_m=downloads&_a=managecategories");

	$interface->staffFooter();
	






/**
* ###############################################
* INSERT CATEGORY
* ###############################################
*/
} else if ($eventaction == "insertcategory") {
	if ($_POST["step"] == 1 && $_SWIFT["staff"]["dlcaninsertcat"] != "0")
	{
		if (trim($_POST["title"]) == "" || trim($_POST["displayorder"]) == "")
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if (!count($_POST["tgroupid"])) {
			$errormessage = $_SWIFT["language"]["selectonetgroup"];
		} else {
			$_POST["displayorder"] = iif(empty($_POST["displayorder"]), "1", $_POST["displayorder"]);	

			insertDownloadsCategory($_POST["parentcategoryid"], $_POST["title"], $_POST["displayorder"], iif($_POST["categorytype"]==1, SWIFTPUBLIC, SWIFTPRIVATE), $_POST["tgroupid"]);

			printRedirect(sprintf($_SWIFT["language"]["dlinsertconfirm"], htmlspecialchars($_POST["title"])), "index.php?_m=downloads&_a=managecategories&insertcat=".urlencode($_POST["title"]));
			exit;
		}
	} else if ($_SWIFT["staff"]["dlcaninsertcat"] == "0") {
		$errormessage = $_SWIFT["language"]["nopermission"];
	}

	$interface->staffHeader($_SWIFT["language"]["downloads"]." &gt; ".$_SWIFT["language"]["insertcategory"], 5);

	$interface->staffNavBar('<a href="index.php?_m=downloads&_a=managecategories" title="'.$_SWIFT["language"]["managecategories"].'">'.$_SWIFT["language"]["managecategories"].'</a> &raquo; '.'<a href="index.php?_m=downloads&_a=insertcategory" title="'.$_SWIFT["language"]["insertcategory"].'">'.$_SWIFT["language"]["insertcategory"].'</a>', "", 5);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	renderDownloadsCatForm(INSERT);
	
	$template->assign("backurl", "index.php?_m=downloads&_a=managecategories");

	$interface->staffFooter();




/**
* ###############################################
* MANAGE FILES
* ###############################################
*/
} else if ($eventaction == "managefiles") {
	if ($_GET["do"] == "delete" && !empty($_GET["downloaditemid"]) && $_SWIFT["staff"]["dlcandelfile"] != "0")
	{
		$infomessage = $_SWIFT["language"]["dlitemdelconfirm"];

		deleteDownloadFiles(array($_GET["downloaditemid"]));
	}

	if (!empty($_REQUEST["insertitem"]))
	{
		$infomessage = sprintf($_SWIFT["language"]["dliteminsertconfirm"], htmlspecialchars($_REQUEST["insertitem"]));
	}

	unset($wheresql); unset($whereadsql);
	if ($_GET["filter"] == "1" && !empty($_GET["filterdownloadcategoryid"]))
	{
		$subcategories = fetchChildCategories($_GET["filterdownloadcategoryid"], ($_temp = array()));
		$subcategories[] = intval($_GET["filterdownloadcategoryid"]);
		$wheresql = " WHERE downloaditems.downloadcategoryid IN (". buildIN($subcategories) .")";
	}
	
	$options["recordsperpage"] = "10";
	$options["sortby"] = "downloaditems.displayorder";
	$options["sortorder"] = "asc";
	$options["massaction"][0]["title"] = $_SWIFT["language"]["delete"];
	$options["massaction"][0]["callback"] = "_maDeleteDownloadItems";

	$options["idname"] = "downloaditemid";
	$options["quicksearch"] = true;

	$options["advancedsearch"][0]["title"] = $_SWIFT["language"]["dlitemtitle"];
	$options["advancedsearch"][0]["query"] = 'SELECT *, downloaditems.displayorder AS itemdisplayorder, downloaditems.title AS itemtitle, downloaditems.dateline AS itemdateline FROM `'. TABLE_PREFIX .'downloaditems` AS downloaditems LEFT JOIN `'. TABLE_PREFIX .'downloadcategories` AS downloadcategories ON (downloaditems.downloadcategoryid = downloadcategories.downloadcategoryid) WHERE downloaditems.title LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["advancedsearch"][1]["title"] = $_SWIFT["language"]["dlitemdesc"];
	$options["advancedsearch"][1]["query"] = 'SELECT *, downloaditems.displayorder AS itemdisplayorder, downloaditems.title AS itemtitle, downloaditems.dateline AS itemdateline FROM `'. TABLE_PREFIX .'downloaditems` AS downloaditems LEFT JOIN `'. TABLE_PREFIX .'downloaddesc` AS downloaddesc ON (downloaditems.downloaditemid = downloaddesc.downloaditemid) LEFT JOIN `'. TABLE_PREFIX .'downloadcategories` AS downloadcategories ON (downloaditems.downloadcategoryid = downloadcategories.downloadcategoryid) WHERE downloaddesc.description LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["callback"] = "_downloadItemFields";

	$options["toolbar"][0]["title"] = $_SWIFT["language"]["insertfile"];
	$options["toolbar"][0]["url"] = "index.php?_m=downloads&_a=insertfile";

	$options["toolbar"][1]["title"] = $_SWIFT["language"]["managecategories"];
	$options["toolbar"][1]["url"] = "index.php?_m=downloads&_a=managecategories";

	$fields[0]["name"] = "downloaditems.title";
	$fields[0]["title"] = $_SWIFT["language"]["dlitemtitle"];
	$fields[0]["width"] = "";

	$fields[1]["name"] = "downloaditems.filename";
	$fields[1]["title"] = $_SWIFT["language"]["dlitemfilename"];
	$fields[1]["width"] = "100";
	$fields[1]["align"] = "center";

	$fields[2]["name"] = "downloaditems.filesize";
	$fields[2]["title"] = $_SWIFT["language"]["dlitemfilesize"];
	$fields[2]["width"] = "90";
	$fields[2]["align"] = "center";

/*
	$fields[3]["name"] = "downloaditems.dateline";
	$fields[3]["title"] = $_SWIFT["language"]["date"];
	$fields[3]["width"] = "150";
	$fields[3]["align"] = "center";*/

	$fields[3]["name"] = "downloaditems.displayorder";
	$fields[3]["title"] = $_SWIFT["language"]["dlcatdisporder"];
	$fields[3]["width"] = "120";
	$fields[3]["align"] = "center";

	$fields[4]["name"] = "downloaditems.totaldownloads";
	$fields[4]["title"] = $_SWIFT["language"]["dltotaldownloads"];
	$fields[4]["width"] = "120";
	$fields[4]["align"] = "center";

	$fields[5]["type"] = "custom";
	$fields[5]["name"] = "options";
	$fields[5]["title"] = $_SWIFT["language"]["options"];
	$fields[5]["width"] = "150";
	$fields[5]["align"] = "center";

	$grid = new Grid();

	$interface->staffHeader($_SWIFT["language"]["downloads"]." &gt; ".$_SWIFT["language"]["managefiles"], 5);

	$interface->staffNavBar('<a href="index.php?_m=downloads&_a=managecategories" title="'.$_SWIFT["language"]["managecategories"].'">'.$_SWIFT["language"]["managecategories"].'</a> &raquo; <a href="index.php?_m=downloads&_a=managefiles" title="'.$_SWIFT["language"]["managefiles"].'">'.$_SWIFT["language"]["managefiles"].'</a>', "", 5);

	$grid->start("downloaditems", $_SWIFT["language"]["dlitemlist"], 'SELECT *, downloaditems.displayorder AS itemdisplayorder, downloaditems.title AS itemtitle, downloaditems.dateline AS itemdateline FROM `'. TABLE_PREFIX .'downloaditems` AS downloaditems LEFT JOIN `'. TABLE_PREFIX .'downloadcategories` AS downloadcategories ON (downloaditems.downloadcategoryid = downloadcategories.downloadcategoryid)'. $wheresql .' $_sortjoin;', 'SELECT COUNT(*) AS totalitems FROM `'. TABLE_PREFIX .'downloaditems` AS downloaditems'. $wheresql .';', 'SELECT *, downloaditems.displayorder AS itemdisplayorder, downloaditems.title AS itemtitle, downloaditems.dateline AS itemdateline FROM `'. TABLE_PREFIX .'downloaditems` AS downloaditems LEFT JOIN `'. TABLE_PREFIX .'downloadcategories` AS downloadcategories ON (downloaditems.downloadcategoryid = downloadcategories.downloadcategoryid) WHERE downloaditems.title LIKE \'%$_searchstr%\' $_sortjoin;', $fields, $options);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	$grid->display("downloaditems");

	echo '<BR /><span class="smalltext">'. $_SWIFT["language"]["legend"] .'<img src="'. $_SWIFT["themepath"] .'icon_public.gif" border="0" /> '. $_SWIFT["language"]["public"] .'&nbsp;&nbsp;&nbsp; <img src="'. $_SWIFT["themepath"] .'icon_private.gif" border="0" /> '. $_SWIFT["language"]["private"] .'&nbsp;&nbsp;&nbsp; <img src="'. $_SWIFT["themepath"] .'icon_lock.gif" border="0" /> '. $_SWIFT["language"]["passprotected"] .'&nbsp;&nbsp;&nbsp;';
	
	$interface->staffFooter();



/**
* ###############################################
* INSERT FILE
* ###############################################
*/
} else if ($eventaction == "insertfile") {
	if ($_POST["step"] == 1 && $_SWIFT["staff"]["dlcaninsertfile"] != "0")
	{
		if (trim($_POST["title"]) == "" || trim($_POST["displayorder"]) == "")
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if (trim($_POST["password"]) != "" && $_POST["password"] != $_POST["passwordconfirm"]) {
			$errormessage = $_SWIFT["language"]["passworddontmatch"];
			$_POST["password"] = "";
			$_POST["passwordconfirm"] = "";
		} else {
			$_POST["displayorder"] = iif(empty($_POST["displayorder"]), "1", $_POST["displayorder"]);	

			if (empty($_POST["filelink"]))
			{
				// There should be an uploaded file now
				if (!isset($_FILES["downloadfile"]))
				{
					$errormessage = $_SWIFT["language"]["errornofile"];
				} else if ($_FILES["downloadfile"]["error"] == UPLOAD_ERR_INI_SIZE) {
					$errormessage = $_SWIFT["language"]["errorfilesize"];				
				} else if ($_FILES["downloadfile"]["error"] == UPLOAD_ERR_PARTIAL) {
					$errormessage = $_SWIFT["language"]["errorpartialupload"];		
				} else if ($_FILES["downloadfile"]["error"] == UPLOAD_ERR_NO_FILE) {
					$errormessage = $_SWIFT["language"]["errornofile"];
				} else if (!file_exists($_FILES["downloadfile"]["tmp_name"])) {
					$errormessage = $_SWIFT["language"]["errornofile"];
				}
			}

			if (empty($errormessage))
			{
				addDownloadFile($_POST["downloadcategoryid"], $_POST["title"], $_POST["description"], $_POST["filelink"], $_POST["displayorder"], iif($_POST["enablepassword"]==1, $_POST["password"]));
	
				printRedirect(sprintf($_SWIFT["language"]["dliteminsertconfirm"], htmlspecialchars($_POST["title"])), "index.php?_m=downloads&_a=managefiles&insertitem=".urlencode($_POST["title"]));
				exit;
			}
		}
	} else if ($_SWIFT["staff"]["dlcaninsertfile"] == "0") {
		$errormessage = $_SWIFT["language"]["nopermission"];
	}

	$interface->staffHeader($_SWIFT["language"]["downloads"]." &gt; ".$_SWIFT["language"]["insertfile"], 5);

	$interface->staffNavBar('<a href="index.php?_m=downloads&_a=managefiles" title="'.$_SWIFT["language"]["managefiles"].'">'.$_SWIFT["language"]["managefiles"].'</a> &raquo; '.'<a href="index.php?_m=downloads&_a=insertfile" title="'.$_SWIFT["language"]["insertfile"].'">'.$_SWIFT["language"]["insertfile"].'</a>', "", 5);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	renderDownloadItemsForm(INSERT);
	
	$template->assign("backurl", "index.php?_m=downloads&_a=managefiles");

	$interface->staffFooter();




/**
* ###############################################
* EDIT CATEGORY
* ###############################################
*/
} else if ($eventaction == "editcategory") {
	$_downloadcategory = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."downloadcategories` WHERE `downloadcategoryid` = '". intval($_REQUEST["downloadcategoryid"]) ."';");
	if (empty($_downloadcategory["downloadcategoryid"]))
	{
		trigger_error($_SWIFT["language"]["invaliddlcat"], E_USER_ERROR);
	}

	if ($_POST["step"] == 1 && $_SWIFT["staff"]["dlcaneditcat"] != "0")
	{
		if (trim($_POST["title"]) == "" || trim($_POST["displayorder"]) == "")
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if (!count($_POST["tgroupid"])) {
			$errormessage = $_SWIFT["language"]["selectonetgroup"];
		} else {
			$_POST["displayorder"] = iif(empty($_POST["displayorder"]), "1", $_POST["displayorder"]);	

			updateDownloadsCategory($_downloadcategory["downloadcategoryid"], $_POST["parentcategoryid"], $_POST["title"], $_POST["displayorder"], iif($_POST["categorytype"]==1, SWIFTPUBLIC, SWIFTPRIVATE), $_POST["tgroupid"]);

			printRedirect(sprintf($_SWIFT["language"]["dlupdateconfirm"], htmlspecialchars($_POST["title"])), "index.php?_m=downloads&_a=managecategories&updatecat=".urlencode($_POST["title"]));
			exit;
		}
	} else if ($_SWIFT["staff"]["dlcaneditcat"] == "0") {
		$errormessage = $_SWIFT["language"]["nopermission"];
	}

	$_POST = array_merge($_POST, $_downloadcategory);

	$interface->staffHeader($_SWIFT["language"]["downloads"]." &gt; ".$_SWIFT["language"]["editcategory"], 5);

	$interface->staffNavBar('<a href="index.php?_m=downloads&_a=managecategories" title="'.$_SWIFT["language"]["managecategories"].'">'.$_SWIFT["language"]["managecategories"].'</a> &raquo; '.'<a href="index.php?_m=downloads&_a=editcategory&downloadcategoryid='. intval($_downloadcategory["downloadcategoryid"]) .'" title="'.$_SWIFT["language"]["editcategory"].'">'.$_SWIFT["language"]["editcategory"].'</a>', "", 5);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	renderDownloadsCatForm(EDIT);
	
	$template->assign("backurl", "index.php?_m=downloads&_a=managecategories");

	$interface->staffFooter();





/**
* ###############################################
* EDIT DOWNLOAD FILE
* ###############################################
*/
} else if ($eventaction == "editfile") {
	$_downloaditem = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."downloaditems` AS downloaditems LEFT JOIN `". TABLE_PREFIX ."downloaddesc` AS downloaddesc ON (downloaditems.downloaditemid = downloaddesc.downloaditemid) WHERE downloaditems.downloaditemid = '". intval($_REQUEST["downloaditemid"]) ."';");
	if (empty($_downloaditem["downloaditemid"]))
	{
		trigger_error($_SWIFT["language"]["invaliddlitem"], E_USER_ERROR);
	}

	if ($_POST["step"] == 1 && $_SWIFT["staff"]["dlcaneditfile"] != "0")
	{
		if (trim($_POST["title"]) == "" || trim($_POST["displayorder"]) == "")
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if (trim($_POST["password"]) != "" && $_POST["password"] != $_POST["passwordconfirm"]) {
			$errormessage = $_SWIFT["language"]["passworddontmatch"];
			$_POST["password"] = "";
			$_POST["passwordconfirm"] = "";
		} else {
			$_POST["displayorder"] = iif(empty($_POST["displayorder"]), "1", $_POST["displayorder"]);	

			if (empty($_POST["filelink"]) && isset($_FILES["downloadfile"]["filename"]))
			{
				// There should be an uploaded file now
				if ($_FILES["downloadfile"]["error"] == UPLOAD_ERR_INI_SIZE) {
					$errormessage = $_SWIFT["language"]["errorfilesize"];
				} else if ($_FILES["downloadfile"]["error"] == UPLOAD_ERR_PARTIAL) {
					$errormessage = $_SWIFT["language"]["errorpartialupload"];
				} else if ($_FILES["downloadfile"]["error"] == UPLOAD_ERR_NO_FILE) {
					$errormessage = $_SWIFT["language"]["errornofile"];
				}
			}

			if (empty($errormessage))
			{
				updateDownloadFile($_downloaditem["downloaditemid"], $_POST["downloadcategoryid"], $_POST["title"], $_POST["description"], $_POST["filelink"], $_POST["displayorder"],$_POST["enablepassword"], iif($_POST["enablepassword"]==1, $_POST["password"]));

				if ($_POST["downloadcategoryid"] != $_downloaditem["downloadcategoryid"])
				{
					recountDownloadCategory($_downloaditem["downloadcategoryid"]);
				}
	
				printRedirect(sprintf($_SWIFT["language"]["dlitemupdateconfirm"], htmlspecialchars($_POST["title"])), "index.php?_m=downloads&_a=managefiles&updateitem=".urlencode($_POST["title"]));
				exit;
			}
		}
	} else if ($_SWIFT["staff"]["dlcaneditfile"] == "0") {
		$errormessage = $_SWIFT["language"]["nopermission"];
	}


	$_POST = array_merge($_POST, $_downloaditem);

	$interface->staffHeader($_SWIFT["language"]["downloads"]." &gt; ".$_SWIFT["language"]["editfile"], 5);

	$interface->staffNavBar('<a href="index.php?_m=downloads&_a=managefiles" title="'.$_SWIFT["language"]["managefiles"].'">'.$_SWIFT["language"]["managefiles"].'</a> &raquo; '.'<a href="index.php?_m=downloads&_a=editfile&downloaditemid='. intval($_downloaditem["downloaditemid"]) .'" title="'.$_SWIFT["language"]["editfile"].'">'.$_SWIFT["language"]["editfile"].'</a>', "", 5);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	renderDownloadItemsForm(EDIT);
	
	$template->assign("backurl", "index.php?_m=downloads&_a=managefiles");

	$interface->staffFooter();
/**
* ###############################################
* DOWNLOAD FILE
* ###############################################
*/
} else if ($eventaction == "downloadfile") {

//	echo "Download ID" . intval($_REQUEST["downloaditemid"]);
	$_downloaditem = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."downloaditems` AS downloaditems LEFT JOIN `". TABLE_PREFIX ."downloaddesc` AS downloaddesc ON (downloaditems.downloaditemid = downloaddesc.downloaditemid) WHERE downloaditems.downloaditemid = '". intval($_REQUEST["downloaditemid"]) ."';");
	if (empty($_downloaditem["downloaditemid"]))
	{
		trigger_error($_SWIFT["language"]["dlierror"], E_USER_ERROR);
	}

	// Is it a link?
	if (!empty($_downloaditem["filelink"]))
	{
		header("location: ".$_downloaditem["filelink"]);
		exit;
	}

	if (!file_exists("./files/".$_downloaditem["storedfilename"]))
	{
		trigger_error($_SWIFT["language"]["dliinvalidfile"], E_USER_ERROR);
	}

	if(isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])) {
		// IE Bug in download name workaround
		ini_set( 'zlib.output_compression','Off' );
	}

	// Get the file extension
	$extension = getFileExtension($_downloaditem["filename"]);
	if (!empty($mimelist[$extension]))
	{
		header("Content-Type: " . $mimelist[$extension] . SWIFT_CRLF);
	} else {
		header("Content-Type: application/force-download");
	}

	if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")){
		header("Content-Disposition: attachment; filename=\"". $_downloaditem["filename"] ."\"");
	} else{
		header("Content-Disposition: attachment; filename=\"". $_downloaditem["filename"] ."\"");
	}

	header("Content-Transfer-Encoding: binary");
	header("Content-Length: ". filesize("./files/".$_downloaditem["storedfilename"]));

	// Yes, just read out the file
	$fp = fopen("./files/".$_downloaditem["storedfilename"], "rb");
	if (!$fp)
	{
		return false;
	}

	while(!feof($fp)) {
		echo fread($fp, 8192);
		flush();
	}

	fclose($fp);
}


?>